import HttpRequest, { type HttpRequestConfig } from "luch-request";
import { useAccountStore } from "@/stores/account";
import { toLoginPage } from "@/utils";

// 全局配置修改 https://www.quanzhan.co/luch-request/guide/3.x/#全局配置修改setconfig
const HttpInstance = new HttpRequest({
  baseURL: import.meta.env.VITE_API_URL, // 请求的根域名
  enableHttp2: true, // 开启 http2
  enableQuic: true, // 开启 quic
  enableCache: true, // 开启 cache
});

// 请求拦截 https://www.quanzhan.co/luch-request/guide/3.x/#在请求之前拦截
HttpInstance.interceptors.request.use((config) => {
  let { token } = useAccountStore();
  // #ifdef H5
  // 优先使用URL存在的token，并更新登录状态
  const searchParams = new URLSearchParams(window.location.search);
  if(searchParams.has("token")) token = searchParams.get("token");
  // #endif
  config.header = Object.assign({ token, authorization: token }, config.header);
  return config;
});

// 响应拦截 https://www.quanzhan.co/luch-request/guide/3.x/#在请求之后拦截
HttpInstance.interceptors.response.use(
  (response) => {
    // 2xx 范围内的状态码都会触发该函数。
    return response;
  },
  (response) => {
    // 超出 2xx 范围的状态码都会触发该函数。
    const { statusCode } = response;

    switch (statusCode) {
      case 401:
        // 跳转登陆页
        toLoginPage();
        break;
      default:
        statusCode && uni.showToast({ title: `${statusCode}：请求异常`, icon: "none" });
        break;
    }
    return Promise.reject(response);
  },
);

async function request<T = any>(url: string, options?: HttpRequestConfig): Promise<T> {
  const { data } = await HttpInstance.middleware<API.Response<T>>({
    url,
    ...options,
  });

  if(data.meta) {
    if(data.meta.code == 200 ){
      if(typeof data.data == "boolean") uni.showToast({ title: data.meta.msg, icon: 'none', duration: 3000 });
      return data.data
    } else {
      uni.showToast({ title: data.meta.msg || '操作失败，请重试', icon: 'none', duration: 3000 });
      return Promise.reject(data);
    }
  } else {
    if(data.code == 401) {
      useAccountStore().token= "";
      // #ifdef H5
      if(url != "/api/user/info") {
        uni.showModal({
          title:'提示',
          content:'登录失效,请重新登录',
          cancelText:'稍后再说',
          confirmText:'立即登录',
          success: ({ confirm }) => {
            if(confirm) toLoginPage();
          }
        })
      }
      // #endif
    }else  {
      uni.showToast({ title: data.msg || '操作失败，请重试', icon: 'none', duration: 3000 });
    }
    return Promise.reject(data);
  }
}

export { request };
